package persistent

import (
	"context"
	"time"

	"gorm.io/gorm"
)

const TableNameNode = "node"

type NodeClient struct {
	db *gorm.DB `name:"saas_db"`
}

func NewNodeClient(db *gorm.DB) *NodeClient {
	return &NodeClient{db: db}
}

func (w *NodeClient) CreateTX(ctx context.Context, po Node, tx *gorm.DB) (err error) {
	return tx.WithContext(ctx).Create(&po).Error
}

func (w *NodeClient) UpdateTX(ctx context.Context, po Node, tx *gorm.DB) (err error) {
	return tx.WithContext(ctx).Model(&po).Updates(&po).Error
}

func (w *NodeClient) QueryNodeByIDTX(ctx context.Context, id string, tx *gorm.DB) (result Node, err error) {
	return result, tx.WithContext(ctx).Take(&result, "id = ?", id).Error
}

func (w *NodeClient) DeleteNodeByCondTX(ctx context.Context, workflowID string, tx *gorm.DB) (err error) {
	return tx.WithContext(ctx).Where("workflow_id = ?", workflowID).Delete(&Node{}).Error
}

func (w *NodeClient) QueryNodesByCondTX(ctx context.Context, cond Node, tx *gorm.DB) (result []Node, err error) {
	return result, tx.WithContext(ctx).Where(&cond).Find(&result).Error
}

// QueryNodesByWorkflowID 根据工作流ID查询所有节点
func (w *NodeClient) QueryNodesByWorkflowID(ctx context.Context, workflowID string) (result []Node, err error) {
	err = w.db.WithContext(ctx).Where("workflow_id = ?", workflowID).Find(&result).Error
	return result, err
}

type Node struct {
	ID             string `gorm:"column:id;type:varchar(64);primaryKey;comment:Snowflake ID | 全局唯一ID"`
	Status         int    `gorm:"column:status;type:tinyint(5)"`
	WorkflowID     string `gorm:"column:workflow_id;type:varchar(64);"`
	NodeTemplateID string `gorm:"column:node_template_id;type:varchar(64)"`

	CreatedAt time.Time `gorm:"column:created_at;comment:Created Time | 创建时间" json:"created_at"`
	UpdatedAt time.Time `gorm:"column:updated_at;comment:Updated Time | 更新时间" json:"updated_at"`
}

func (w Node) TableName() string {
	return TableNameNode
}
